package com.squirrel.michale.test02;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;


/**
 * @author guanhao 观浩
 * @version v1.0.0.0
 * @createTime 2023/3/10 20:22
 * @company Michale Squirrel
 * @link
 * @description
 */
public class Solution {


    int logAnalysis(String[] logs, int depth) {
        HashMap<Integer, Node> nodes = new HashMap<>();
        for (int i = 0; i < logs.length; i++) {
            String log = logs[i];
            String[] split = log.split("\\|");
                Integer processId = Integer.valueOf(split[2]);
                Node parent = null;
                if (nodes.get(processId) == null) {
                    parent = new Node(processId);
                    nodes.put(processId, parent);
                }else{
                    parent = nodes.get(processId);
                }

                String[] subProcessInfo = split[3].split(" ");
                if (subProcessInfo.length == 2 && "START".equals(subProcessInfo[0])) {
                    String regularEx = "^[1-9][0-9]{0,4}";
                    Pattern regular = Pattern.compile(regularEx);
                    if (regular.matcher(subProcessInfo[1]).matches()) {
                        Integer subProcessId = Integer.valueOf(subProcessInfo[1]);
                        Node child = null;
                        if (nodes.get(subProcessId) == null) {
                            child = new Node(subProcessId);
                        } else {
                            child = nodes.get(subProcessId);
                            parent.nexts.add(child);
                        }
                    }

                }
        }
        int result = 0;
        int curDepth = 1;

        for (Integer integer : nodes.keySet()) {
            Node node = nodes.get(integer);
            if (node.nexts.size() >0) {
                curDepth++;
                if (curDepth == depth) {
                    result += node.nexts.size();
                }
            }
        }
        return result;
    }




    class Node {
        public int value;
        public ArrayList<Node> nexts;

        public Node(int value) {
            this.value = value;
            nexts = new ArrayList<>();
        }
    }
}
